package com.gears_software.sxdc.dccx.ui.activity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.nearby.NearbyInfo;
import com.amap.api.services.nearby.NearbySearch;
import com.amap.api.services.nearby.NearbySearchFunctionType;
import com.amap.api.services.nearby.NearbySearchResult;
import com.amap.api.services.nearby.UploadInfo;
import com.amap.api.services.nearby.UploadInfoCallback;
import com.gears_software.sxdc.dccx.R;
import com.gears_software.sxdc.dccx.data.finder.IZPOrderFinder;
import com.gears_software.sxdc.dccx.data.finder.util.GearsErrorHandler;
import com.gears_software.sxdc.dccx.data.model.LatLonListModel;
import com.gears_software.sxdc.dccx.data.model.PositionEntity;
import com.gears_software.sxdc.dccx.data.model.ResultModel;
import com.gears_software.sxdc.dccx.data.service.TestService;
import com.gears_software.sxdc.dccx.ui.map.LocationTask;
import com.gears_software.sxdc.dccx.ui.map.OnLocationGetListener;
import com.gears_software.sxdc.dccx.ui.map.RegeocodeTask;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.orhanobut.logger.Logger;
import com.sdsmdg.tastytoast.TastyToast;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.rest.spring.annotations.RestService;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by chezhenzhen on 2017/9/11.
 */

@EActivity(R.layout.activity_test)
public class TestActivity extends AppCompatActivity implements NearbySearch.NearbyListener {
    @ViewById
    TextView txt_show;
    @ViewById
    SeekBar sb;
    @ViewById
    TextView tv;
    @ViewById
    TextView tx_jt;
    @RestService
    IZPOrderFinder izpOrderFinder;
    @Bean
    GearsErrorHandler errorHandler;
    NearbySearch mNearbySearch;
    // 语音合成对象
    private SpeechSynthesizer mTts;
    Context context;
    double a = 0.000001;
    PositionEntity entity;

    @AfterViews
    void created() {
        context = this;

        izpOrderFinder.setRestErrorHandler(errorHandler);
        //获取附近实例（单例模式）
        mNearbySearch = NearbySearch.getInstance(this);
        //设置附近监听
        mNearbySearch.addNearbyListener(this);

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (seekBar.getProgress() == seekBar.getMax()) {
                    tv.setVisibility(View.VISIBLE);
                    tv.setText("完成验证");
                } else {
//                    tv.setVisibility(View.INVISIBLE);
                    tv.setText("请按住滑块，拖动到最右边");
                    tx_jt.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (seekBar.getProgress() != seekBar.getMax()) {
                    seekBar.setProgress(0);
                    tv.setVisibility(View.VISIBLE);
                    tx_jt.setVisibility(View.INVISIBLE);
                    tv.setText("请按住滑块，拖动到最右边");
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (seekBar.getProgress() != seekBar.getMax()) {
                    seekBar.setProgress(0);
                    tv.setVisibility(View.VISIBLE);
                    tx_jt.setVisibility(View.VISIBLE);
                    tv.setText("到达约定地点");
                }
            }
        });


    }

    Intent testintent;

    @Click
    void btn_connect() {
        testintent = new Intent(this, TestService.class);
        this.startService(testintent);

    }

    @Click
    void btn_discon() {
        if (testintent != null) {
            stopService(testintent);
        }
    }


    @Click
    void btn_bobao() {
        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(this, null);
        //2.合成参数设置，详见《科大讯飞MSC API手册(Android)》SpeechSynthesizer 类
        mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");//设置发音人
        mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速
        mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量，范围0~100
        mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
        //设置合成音频保存位置（可自定义保存位置），保存在“./sdcard/iflytek.pcm”
        //保存在SD卡需要在AndroidManifest.xml添加写SD卡权限
        //如果不需要保存合成音频，注释该行代码
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
        //3.开始合成
        mTts.startSpeaking("科大讯飞，让世界聆听我们的声音", mSynListener);
    }

    //合成监听器
    private SynthesizerListener mSynListener = new SynthesizerListener() {
        //会话结束回调接口，没有错误时，error为null
        public void onCompleted(SpeechError error) {
        }

        //缓冲进度回调
        //percent为缓冲进度0~100，beginPos为缓冲音频在文本中开始位置，endPos表示缓冲音频在文本中结束位置，info为附加信息。
        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
        }

        //开始播放
        public void onSpeakBegin() {
        }

        //暂停播放
        public void onSpeakPaused() {
        }

        //播放进度回调
        //percent为播放进度0~100,beginPos为播放音频在文本中开始位置，endPos表示播放音频在文本中结束位置.
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

        //恢复播放回调接口
        public void onSpeakResumed() {
        }

        //会话事件回调接口
        public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
        }
    };

    @Click
    void btn_upload() {
        //构造上传位置信息
//        UploadInfo loadInfo = new UploadInfo();
//        //设置上传位置的坐标系支持AMap坐标数据与GPS数据
//        loadInfo.setCoordType(NearbySearch.AMAP);
//        //设置上传数据位置,位置的获取推荐使用高德定位sdk进行获取
////        loadInfo.setPoint(new LatLonPoint(37.807282, 112.55553));
//        loadInfo.setPoint(new LatLonPoint(37.80757, 112.565161));
//        //设置上传用户id
//        loadInfo.setUserID("01");
//        //调用异步上传接口
//        mNearbySearch.uploadNearbyInfoAsyn(loadInfo);

        mNearbySearch.startUploadNearbyInfoAuto(new UploadInfoCallback() {
            //设置自动上传数据和上传的间隔时间
            @Override
            public UploadInfo OnUploadInfoCallback() {
                UploadInfo loadInfo = new UploadInfo();
                loadInfo.setCoordType(NearbySearch.AMAP);
                //位置信息
                loadInfo.setPoint(new LatLonPoint(entity.getLatitue() + a, entity.getLongitude()));
                a = a * -1;
                //用户id信息
                loadInfo.setUserID("czzltp");
                return loadInfo;
            }
        }, 8000);
    }

    @Click
    void btn_upload2() {
        //构造上传位置信息
        UploadInfo loadInfo = new UploadInfo();
        //设置上传位置的坐标系支持AMap坐标数据与GPS数据
        loadInfo.setCoordType(NearbySearch.AMAP);
        //设置上传数据位置,位置的获取推荐使用高德定位sdk进行获取
        loadInfo.setPoint(new LatLonPoint(37.805815, 112.568444));
        //设置上传用户id
        loadInfo.setUserID("aaaaa");
        //调用异步上传接口
        mNearbySearch.uploadNearbyInfoAsyn(loadInfo);
    }

    @Click
    void btn_upload3() {
        //构造上传位置信息
        UploadInfo loadInfo = new UploadInfo();
        //设置上传位置的坐标系支持AMap坐标数据与GPS数据
        loadInfo.setCoordType(NearbySearch.AMAP);
        //设置上传数据位置,位置的获取推荐使用高德定位sdk进行获取
        loadInfo.setPoint(new LatLonPoint(37.807985, 112.570268));
        //设置上传用户id
        loadInfo.setUserID("03");
        //调用异步上传接口
        mNearbySearch.uploadNearbyInfoAsyn(loadInfo);
    }

    @Click
    void btn_read() {
        //设置搜索条件
        NearbySearch.NearbyQuery query = new NearbySearch.NearbyQuery();
        //设置搜索的中心点
        query.setCenterPoint(new LatLonPoint(37.806737, 112.56802));
        //设置搜索的坐标体系
        query.setCoordType(NearbySearch.AMAP);
        //设置搜索半径
        query.setRadius(3000);
        //设置查询的时间
        query.setTimeRange(30);
        //设置查询的方式驾车还是距离
        query.setType(NearbySearchFunctionType.DRIVING_DISTANCE_SEARCH);
        //调用异步查询接口
        mNearbySearch.searchNearbyInfoAsyn(query);
    }

    @Click
    void btn_getIP() {
        GetNetIp();
    }

    @Click
    void btn_impl() {
getLatLonList();
    }

    @Background
    void getLatLonList() {
        ResultModel<LatLonListModel> res = izpOrderFinder.getLonLatList("Uv2prTljiFEG3e_7GH3WKXPW6zcpqBmg", "", "");
        showLatLonResult(res);
    }

    @UiThread
    void showLatLonResult(ResultModel<LatLonListModel> res) {
        if (res != null){
            if (res.getErrno().equals("0")){
                TastyToast.makeText(this,res.getErrmsg(),TastyToast.LENGTH_SHORT,TastyToast.DEFAULT);
            }
        }
    }

    //获取内网地址
    public String getIP(Context context) {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * 获取外网IP地址
     */
    @Background
    void GetNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String line = "";
        try {
            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
            URLConnection connection = infoUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                while ((line = reader.readLine()) != null)
                    strber.append(line + "\n");
                inStream.close();
                // 从反馈的结果中提取出IP地址
                int start = strber.indexOf("{");
                int end = strber.indexOf("}");
                String json = strber.substring(start, end + 1);
                if (json != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        line = jsonObject.optString("cip");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                showResult(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @UiThread
    void showResult(String line) {
        Logger.d("本机ip地址:" + line);

    }

    @Override
    public void onUserInfoCleared(int i) {

    }

    @Override
    public void onNearbyInfoSearched(NearbySearchResult nearbySearchResult, int resultCode) {
        //搜索周边附近用户回调处理
        if (resultCode == 1000) {
            if (nearbySearchResult != null && nearbySearchResult.getNearbyInfoList() != null && nearbySearchResult.getNearbyInfoList().size() > 0) {
                NearbyInfo nearbyInfo = nearbySearchResult.getNearbyInfoList().get(0);
                txt_show.setText("周边搜索结果为size " + nearbySearchResult.getNearbyInfoList().size() +
                        " first：" + nearbyInfo.getUserID() + "  " + nearbyInfo.getDistance() + "  "
                        + nearbyInfo.getDrivingDistance() + "  " + nearbyInfo.getTimeStamp() + "  " + nearbyInfo.getPoint().toString());
                Logger.d("周边搜索结果为size " + nearbySearchResult.getNearbyInfoList().size() +
                        " first：" + nearbyInfo.getUserID() + "  " + nearbyInfo.getDistance() + "  "
                        + nearbyInfo.getDrivingDistance() + "  " + nearbyInfo.getTimeStamp() + "  " + nearbyInfo.getPoint().toString());
            } else {
                txt_show.setText("周边搜索结果为空");
                Logger.d("周边搜索结果为空");
            }
        } else {
            Logger.d("周边搜索出现异常，异常码为：" + resultCode);
        }
    }

    @Override
    public void onNearbyInfoUploaded(int i) {
        txt_show.setText("上传返回code：" + i);
        Logger.d("上传返回code：  " + i);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mNearbySearch.destroy();

    }

    //需要申请GETTask权限
    private boolean isApplicationBroughtToBackground() {
        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(getPackageName())) {
                return true;
            }
        }
        return false;
    }


//    public boolean wasBackground = false;    //声明一个布尔变量,记录当前的活动背景
//
//    @Override
//    public void onPause() {
//        super.onPause();
//        if (isApplicationBroughtToBackground())
//            wasBackground = true;
//    }
//
//    public void onResume() {
//        super.onResume();
//        if (wasBackground) {//
//            Log.e("aa", "从后台回到前台");
//        }
//        wasBackground = false;
//    }

//    public boolean IsForeground(Context context) {
//        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
//        if (tasks != null && !tasks.isEmpty()) {
//            ComponentName topActivity = tasks.get(0).topActivity;
//            if (topActivity.getPackageName().equals(context.getPackageName())) {
//                return true;
//            }
//        }
//        return false;
//    }
//
//
//    boolean isActive;
//
//    @Override
//    protected void onResume() {
//        if (!isActive) {
//            //app 从后台唤醒，进入前台
//            isActive = true;
//            TastyToast.makeText(this, "程序从后台唤醒", TastyToast.LENGTH_SHORT, TastyToast.CONFUSING);
//        }
//        super.onResume();
//    }
//
//    @Override
//    protected void onStop() {
//        if (!IsForeground(this)) {
//            //app 进入后台
//            isActive = false;//记录当前已经进入后台
//            TastyToast.makeText(this, "程序进入后台", TastyToast.LENGTH_SHORT, TastyToast.CONFUSING);
//        }
//        super.onStop();
//    }

}
